package com.dyj.common.interceptor;

import com.alibaba.fastjson.JSONObject;
import com.dtflys.forest.exceptions.ForestRuntimeException;
import com.dtflys.forest.http.ForestRequest;
import com.dtflys.forest.http.ForestResponse;
import com.dtflys.forest.interceptor.Interceptor;
import com.dyj.common.client.AuthClient;
import com.dyj.common.config.AgentConfiguration;
import com.dyj.common.domain.query.BaseQuery;
import com.dyj.common.domain.vo.TpThirdV2TokenVo;
import com.dyj.common.utils.DyConfigUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.Objects;

/**
 * @author danmo
 * @date 2024-06-24 18:40
 **/
@Component
public class TpThirdV2TokenHeaderInterceptor implements Interceptor<Object> {

    private final Log log = LogFactory.getLog(TpThirdV2TokenHeaderInterceptor.class);

    @Resource
    private AuthClient authClient;

    @Override
    public boolean beforeExecute(ForestRequest request) {
        Integer tenantId = null;
        String clientKey = "";
        Object[] arguments = request.getArguments();
        for (Object argument : arguments) {
            if (argument instanceof BaseQuery) {
                BaseQuery query = (BaseQuery) argument;
                tenantId = query.getTenantId();
                clientKey = query.getClientKey();
            }
        }

        TpThirdV2TokenVo tpThirdV2Token = DyConfigUtils.getAgentTokenService().getTpThirdV2Token(tenantId, clientKey);
        if (Objects.isNull(tpThirdV2Token)) {
            AgentConfiguration agent = DyConfigUtils.getAgent(tenantId, clientKey);
            tpThirdV2Token = authClient.tpThirdV2Token(agent.getClientKey(), agent.getClientSecret(), agent.getTicket());
            if (Objects.nonNull(tpThirdV2Token) && StringUtils.hasLength(tpThirdV2Token.getComponent_access_token())) {
                DyConfigUtils.getAgentTokenService().setTpThirdV2Token(tenantId, clientKey, tpThirdV2Token);
            }
        }

        if (Objects.isNull(tpThirdV2Token)) {
            throw new RuntimeException("component_access_token is null");
        }
        request.addHeader("access-token", tpThirdV2Token.getComponent_access_token());
        return Interceptor.super.beforeExecute(request);
    }

    @Override
    public void onError(ForestRuntimeException ex, ForestRequest request, ForestResponse response) {
        StringBuilder sb = new StringBuilder("TpThirdV2TokenHeaderInterceptor onError ");
        sb.append("url:");
        sb.append(request.getUrl());
        sb.append(", ");
        sb.append("params:");
        sb.append(JSONObject.toJSONString(request.getArguments()));
        sb.append(", ");
        sb.append("result:");
        sb.append(response.getContent());
        sb.append(", ");
        sb.append("msg:");
        sb.append(ex.getMessage());
        log.info(sb.toString());
    }
}
